package com.cd.university.config.security.impl;

import com.cd.university.config.security.validate.ValidateCode;
import com.cd.university.config.security.validate.ValidateCodeRepository;
import com.cd.university.config.security.validate.ValidateCodeType;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 保存在Session的验证码
 * @author 陈栋
 * @create 2021/9/4 18:03
 */
public class SessionValidateCodeRepository implements ValidateCodeRepository {

    /**
     * 验证码放入session时的前缀
     */
    String SESSION_KEY_PREFIX = "SESSION_KEY_FOR_CODE_";

    /**
     * session操控工具
     */
    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    /**
     * 保存在session中
     * @param request 请求和响应
     * @param code 验证码实例
     * @param validateCodeType 验证码的枚举类
     */
    @Override
    public void save(ServletWebRequest request, ValidateCode code, ValidateCodeType validateCodeType) {
        sessionStrategy.setAttribute(request, getSessionKey(request, validateCodeType), code);
    }

    /**
     * 拿到session中的验证吗
     * @param request 请求和响应
     * @param validateCodeType 验证码枚举类
     * @return 验证码实例
     */
    @Override
    public ValidateCode get(ServletWebRequest request, ValidateCodeType validateCodeType) {

        return (ValidateCode) sessionStrategy.getAttribute(request, getSessionKey(request,validateCodeType));
    }

    @Override
    public void remove(ServletWebRequest request, ValidateCodeType validateCodeType) {
        sessionStrategy.removeAttribute(request, getSessionKey(request,validateCodeType));
    }

    /**
     * 构建验证码时放入session时的key
     * @param request 请求和相应
     * @param validateCodeType 验证码的类型
     * @return session的key
     */
    private String getSessionKey(ServletWebRequest request, ValidateCodeType validateCodeType) {
        return SESSION_KEY_PREFIX + validateCodeType.getParamNameOnValidate().toUpperCase();
    }
}
